import React, { useEffect, useState } from 'react'
import { Table, ButtonGroup, Button, Popconfirm, Notification } from '@douyinfe/semi-ui';
import { IconPlus, IconExport } from "@douyinfe/semi-icons"
import { notificationCatchErr } from '../lib/utils';

export default function TableComponents(props) {
    const [loading, setLoading] = useState(false);
    const columns = [...props.columns];

    if (props.withBtn?.operation) {
        columns.push({
            title: '操作',
            dataIndex: 'operation',
            width: "160px",
            render: (_, row) => {
                return <>
                    <ButtonGroup size={'small'}>
                        <Button onClick={() => props.infoApi({ id: row.id })}>编辑</Button>

                        <Button size='small' type='danger'>
                            <Popconfirm
                                size='small'
                                title="确定是否要删除？"
                                content="此操作将不可逆"
                                onConfirm={() => onDeleteConfirm(row.id)}
                            >删除</Popconfirm>
                        </Button>
                    </ButtonGroup>
                </>;
            },
        });
    }


    const getList = function (params) {
        setLoading(true);
        return props.fetchApi(params).then(({ data }) => {
            setItems(data.data);
            setPagination({ ...pagination, total: data.total, currentPage: data.current_page })
            setLoading(false);
        }).catch((e) => {
            setLoading(false)
        });
    }

    const [items, setItems] = useState([]);
    const [pagination, setPagination] = useState({
        "pageSize": 10,
        "total": 0,
        "currentPage": 1,
        "showTotal": true,
        "showSizeChanger": true,
        "onChange": (current, pageSize) => getList({ page: current, pageSize: pageSize })
    });

    useEffect(() => { getList({ page: pagination.currentPage, pageSize: pagination.pageSize }) }, [props.refreshTable]);
    useEffect(() => { getList({ page: 1, pageSize: 10 }) }, []);

    const onDeleteConfirm = (id) => {
        setLoading(true)
        props.deleteApi({ id: id }).then(({ data }) => {
            setLoading(false)
            getList({ page: pagination.currentPage, pageSize: pagination.pageSize })
        }).catch(notificationCatchErr("删除失败"))
    };


    const rowSelection = props.withBtn?.selection ? {
        getCheckboxProps: record => ({
            disabled: record.name === '设计文档', // Column configuration not to be checked
            name: record.name,
        }),
        onSelect: (record, selected) => {
            console.log(`select row: ${selected}`, record);
        },
        onSelectAll: (selected, selectedRows) => {
            console.log(`select all rows: ${selected}`, selectedRows);
        },
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
    } : null;

    return (
        <div className='TableComponents' style={{
            backgroundColor: 'var(--semi-color-bg-0)', padding: '10px'
        }}>

            <div style={{ margin: '10px 0' }}>
                {
                    props.withBtn?.add && <Button onClick={() => props.withBtn?.add()}><IconPlus size='small' />新建</Button>
                }

                {
                    props.withBtn?.export && <Button style={{ float: 'right' }} onClick={() => props.withBtn?.export()}><IconExport size='small' />导出</Button>
                }
            </div>

            <Table
                loading={loading}
                size='small'
                columns={columns}
                dataSource={items}
                rowSelection={rowSelection}
                pagination={pagination} />
        </div >
    )
}
